<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/12
 * Time: 15:08
 */
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Constant\ErrorConstant;
use App\Service\Api\CouponService;
use Illuminate\Support\Facades\Validator;

class CouponController extends BaseController
{
    protected $service;

    public function __construct(Request $request, CouponService $service)
    {
        parent::__construct($request);
        $this->service  =   $service;
    }

    /**
     * 领券中心
     * @return \Illuminate\Http\JsonResponse
     */
    public function centerCoupon()
    {
        [$flag, $result]    =   $this->service->couponCenter();
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_COUPON_CENTER_ERROR, $result);
        }
    }

    /**
     * 用户领取优惠券
     * @return \Illuminate\Http\JsonResponse
     */
    public function fetchCoupon()
    {
        $validator  =   Validator::make($this->request->post(), [
            'coupon_id' =>  'required|integer|exists:mini_coupon,id'
        ], [
            'coupon_id.required'    =>  '优惠券ID不能为空',
            'coupon_id.integer'     =>  '优惠券ID必须为整型',
            'coupon_id.exists'      =>  '优惠券不存在'
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::API_COUPON_FETCH_ERROR, $validator->errors()->first());
        }

        [$flag, $result]    =   $this->service->couponFetch((int) $this->request->post('coupon_id'));
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_COUPON_FETCH_ERROR, $result);
        }
    }

    /**
     * 用户删除优惠券
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteCoupon()
    {
        $validator  =   Validator::make($this->request->post(), [
            'coupon_id'     =>  'required|array'
        ], [
            'coupon_id.required'    =>  '优惠券列表不能为空',
            'coupon_id.array'       =>  '优惠券列表必须为数组',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::API_COUPON_DELETE_ERROR, $validator->errors()->first());
        }

        [$flag, $result]    =   $this->service->couponDelete($this->request->post('coupon_id'));
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_COUPON_DELETE_ERROR, $result);
        }
    }

}
